package com.zzyl.common.ai;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class AIModelInvoker {

    @Autowired
    private AliyunAIProperties aliyunAIProperties;
    public String invokeAliyun(String prompt)  {
        Message build = Message.builder()
                                .role(Role.USER.getValue())
                                .content(prompt).build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(aliyunAIProperties.getApiKey())
                // 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model(aliyunAIProperties.getAliyunModel())
                .messages(Arrays.asList(build))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();


        Generation gen = new Generation();



        try {
            GenerationResult result = gen.call(param);
            String content = result.getOutput().getChoices().get(0).getMessage().getContent();
            content = content.replace("```json", "")
                    .replace("```", "")
                    .trim();
            return content;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
    }



//    private static final String API_URL = "https://qianfan.baidubce.com/v2/chat/completions";
//    private static final String AUTHORIZATION = "Bearer bce-v3/ALTAK-r5PJYayiAuCStsUffUyDo/9522957d22ef70260657360312dc0f827f8e40a1";
//    public String invokeQianfan(String prompt) {
//        try {
//            Map<String, Object> message = Map.of("role", "user", "content", prompt);
//            var messages = new Object[]{message};
//
//            Map<String, Object> bodyMap = new HashMap<>();
//            bodyMap.put("model", "ernie-4.0-8k");
//            bodyMap.put("max_completion_tokens", 2048);
//            bodyMap.put("messages", messages);
//            bodyMap.put("stream", false);
//            bodyMap.put("request_id", IdUtil.fastSimpleUUID());
//            String bodyJson = JSONUtil.toJsonStr(bodyMap);
//            String response = HttpUtil.createRequest(Method.POST, API_URL)
//                    .header("Authorization", AUTHORIZATION)
//                    .header("Content-Type", "application/json")
//                    .header("User-Agent", "Mozilla/5.0 (compatible; Java)")
//                    .body(bodyJson)
//                    .execute()
//                    .body();
//
//            System.out.println(response);
//
//            JSONObject jsonResponse = JSONUtil.parseObj(response);
//            String content = jsonResponse.getByPath("choices[0].message.content", String.class);
//            content = content.replace("```json", "")
//                    .replace("```", "")
//                    .trim();
//            return content;
//        } catch (Exception e) {
//            throw new RuntimeException("调用千帆大模型失败请检查失败原因: " + e.getMessage(), e);
//        }
//    }






